﻿//-----------------------------------------------------------------------
// <copyright file="ComponentCollectorJob.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace TileTool.Base.Component
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.ComponentModel.Composition.Hosting;
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Linq;
    using TileTool.Base.Threading.Job;
    using TileTool.Base.Threading.Job.Generic;
    using TileTool.Component;
    using TileTool.Log;
    using TileTool.PerfSpy;

    /// <summary>
    /// Job which collects all components that are currently exposed.
    /// </summary>
    public class ComponentCollectorJob : Job<IEnumerable<IComponent>>
    {
        #region Constants

        /// <summary>
        /// Log category to use.
        /// </summary>
        private const string LogCategory = "ComponentCollectorJob";

        #endregion

        #region Fields - Private

        /// <summary>
        /// List of all known components.
        /// </summary>
        [ImportMany(typeof(IComponent))]
        private IEnumerable<IComponent> allComponents = Enumerable.Empty<IComponent>();

        #endregion

        #region Methods - Public

        /// <summary>
        /// Called to handle job execution.
        /// </summary>
        public override void HandleExecute()
        {
            using (new TimedBlock("ComponentCollection"))
            {
                string startPath = AppDomain.CurrentDomain.BaseDirectory;

                LogSystem.LogInfo(LogCategory, "Starting component search in: {0}", startPath);

                IEnumerable<string> dirs = this.CollectDirectories(startPath);

                LogSystem.LogInfo(LogCategory, "Building catalogs...");

                AggregateCatalog catalogs = this.BuildCatalogs(dirs);
                CompositionContainer container = new CompositionContainer(catalogs);

                LogSystem.LogInfo(LogCategory, "Satisfy imports...");

                container.SatisfyImportsOnce(this);

                foreach (IComponent comp in this.allComponents)
                {
                    Type type = comp.GetType();
                    LogSystem.LogInfo(LogCategory, "Found component named: {0} - {1} - {2}", comp.Name, type.AssemblyQualifiedName, type.Assembly.Location);
                }

                this.Result = this.allComponents;
            }
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Given a set of directories, build a set of catalogs which looks for assemblies
        /// in those directories.
        /// </summary>
        /// <param name="dirs">Directories to build from.</param>
        /// <returns>Returns an aggregate catalog which wraps all searched directories.</returns>
        private AggregateCatalog BuildCatalogs(IEnumerable<string> dirs)
        {
            IList<DirectoryCatalog> res = new List<DirectoryCatalog>();

            foreach (string dir in dirs)
            {
                res.Add(new DirectoryCatalog(dir));
            }

            return new AggregateCatalog(res);
        }

        /// <summary>
        /// Given a root directory, collect all directories that are under it that
        /// may contain components.
        /// </summary>
        /// <param name="rootDirectory">Directory to start component search at.</param>
        /// <returns>Returns an enumerable of found directories.</returns>
        private IEnumerable<string> CollectDirectories(string rootDirectory)
        {
            IList<string> results = new List<string>();

            this.CollectDirectoriesRecurse(rootDirectory, results);

            return results;
        }

        /// <summary>
        /// Given a root directory, recursively walk all directories under it and add them
        /// to the passed list.
        /// </summary>
        /// <param name="rootDirectory">Directory we are searching.</param>
        /// <param name="dest">Target for all added directories.</param>
        private void CollectDirectoriesRecurse(string rootDirectory, IList<string> dest)
        {
            LogSystem.LogInfo(LogCategory, "Searching for directories in: {0}", rootDirectory);

            try
            {
                IEnumerable<string> dirs = Directory.EnumerateDirectories(rootDirectory);

                // Only add the directory after we have made a successful call to enumerate.
                dest.Add(rootDirectory);

                foreach (string dir in dirs)
                {
                    this.CollectDirectoriesRecurse(dir, dest);
                }
            }
            catch (Exception e)
            {
                LogSystem.LogError(LogCategory, "Failed to enumerate directory {0}: {1}", rootDirectory, e.ToString());
            }
        }

        #endregion
    }
}
